#include "widgets/directionCtl.h"

#include <QDebug>

DirectionCtl::DirectionCtl(QPushButton *btnFront, QPushButton *btnBack, QPushButton *btnLeft, QPushButton *btnRight,
                           std::shared_ptr<AppNode> appNode, QWidget *parent)
    : QWidget(parent), btnFront_(btnFront), btnBack_(btnBack), btnLeft_(btnLeft), btnRight_(btnRight),
      btnFrontPressed_(false), btnBackPressed_(false), btnLeftPressed_(false), btnRightPressed_(false),
      appNode_(appNode) {
    // 方向控制按钮
    connect(btnFront_, &QPushButton::pressed, this, [this]() { btnFrontPressed(true); });
    connect(btnFront_, &QPushButton::released, this, [this]() { btnFrontPressed(false); });

    connect(btnBack_, &QPushButton::pressed, this, [this]() { btnBackPressed(true); });
    connect(btnBack_, &QPushButton::released, this, [this]() { btnBackPressed(false); });

    connect(btnLeft_, &QPushButton::pressed, this, [this]() { btnLeftPressed(true); });
    connect(btnLeft_, &QPushButton::released, this, [this]() { btnLeftPressed(false); });

    connect(btnRight_, &QPushButton::pressed, this, [this]() { btnRightPressed(true); });
    connect(btnRight_, &QPushButton::released, this, [this]() { btnRightPressed(false); });

    connect(&timer_, &QTimer::timeout, this, &DirectionCtl::onTimeout);
    timer_.setInterval(100); // ms
}

DirectionCtl::~DirectionCtl() {}

void DirectionCtl::onTimeout() {
    qDebug("Timeout");
    if (btnFrontPressed_) {
        qDebug("btnFront is pressed");
    }
    if (btnLeftPressed_) {
        qDebug("btnLeft is pressed");
    }
}

void DirectionCtl::startTimer() {
    if (!timer_.isActive()) {
        timer_.start();
    }
}

void DirectionCtl::stopTimer() {
    if (timer_.isActive() && (!btnFrontPressed_ && !btnBackPressed_ && !btnLeftPressed_ && !btnRightPressed_)) {
        timer_.stop();
    }
}

void DirectionCtl::btnFrontPressed(bool isPressed) {
    btnFrontPressed_ = isPressed;
    if (isPressed) {
        qDebug("btnFront is pressed");
        startTimer();
    } else {
        stopTimer();
    }
}

void DirectionCtl::btnBackPressed(bool isPressed) {
    btnBackPressed_ = isPressed;
    if (isPressed) {
        startTimer();
    } else {
        stopTimer();
    }
}

void DirectionCtl::btnLeftPressed(bool isPressed) {
    DirectionCtl::btnLeftPressed_ = isPressed;
    if (isPressed) {
        startTimer();
    } else {
        stopTimer();
    }
}

void DirectionCtl::btnRightPressed(bool isPressed) {
    btnRightPressed_ = isPressed;
    if (isPressed) {
        startTimer();
    } else {
        stopTimer();
    }
}
